package cn.wildfire.chat.kit.contact;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import java.util.ArrayList;
import java.util.List;

import cn.wildfire.chat.app.main.MainActivity;
import cn.wildfire.chat.kit.WfcUIKit;
import cn.wildfire.chat.kit.contact.model.ContactCountFooterValue;
import cn.wildfire.chat.kit.contact.model.FriendRequestValue;
import cn.wildfire.chat.kit.contact.model.HeaderValue;
import cn.wildfire.chat.kit.contact.model.UIUserInfo;
import cn.wildfire.chat.kit.contact.newfriend.FriendRequestListActivity;
import cn.wildfire.chat.kit.contact.newfriend.SearchUserActivity;
import cn.wildfire.chat.kit.contact.viewholder.footer.ContactCountViewHolder;
import cn.wildfire.chat.kit.contact.viewholder.header.AddFriendViewHolder;
import cn.wildfire.chat.kit.contact.viewholder.header.FriendRequestViewHolder;
import cn.wildfire.chat.kit.search.SearchActivity;
import cn.wildfire.chat.kit.user.UserInfoActivity;
import cn.wildfire.chat.kit.user.UserViewModel;
import cn.wildfire.chat.kit.widget.QuickIndexBar;
import cn.wildfirechat.model.UserInfo;

public class ContactListFragment extends BaseUserListFragment implements QuickIndexBar.OnLetterUpdateListener {

    private UserViewModel userViewModel;
    private UserInfo userInfo;

    private Observer<Integer> friendRequestUpdateLiveDataObserver = count -> {
        FriendRequestValue requestValue = new FriendRequestValue(count == null ? 0 : count);
        userListAdapter.updateHeader(1, requestValue);
    };

    private Observer<Object> contactListUpdateLiveDataObserver = o -> {
        loadContacts(true);
    };

    /**
     * modify by HEKE , 2019/8/15 19:19 TODO 调用刷新
     * 当非初次创建时，每次切换联系人界面显示时刷新一次好友信息
     */
    public void loadContacts(boolean refresh) {
        if (contactViewModel == null) {
            return;
        }
        contactViewModel.getContactsAsync(refresh)
                .observe(this, userInfos -> {
                    if (userInfos != null && userInfos.size() > 0) {
                        userListAdapter.setUsers(userInfoToUIUserInfo(userInfos));
                        userListAdapter.notifyDataSetChanged();
                        for (UserInfo info : userInfos) {
                            if (info.name == null || info.displayName == null) {
                                userViewModel.getUserInfo(info.uid, true);
                            }
                        }
                    } else {
                        if (userListAdapter != null) {
                            List<UIUserInfo> nullList = new ArrayList<>();
                            userListAdapter.setUsers(nullList);
                            userListAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }

    private Observer<List<UserInfo>> userInfoLiveDataObserver = userInfos -> {
        userListAdapter.updateContacts(userInfoToUIUserInfo(userInfos));
    };

    @Override
    public void onResume() {
        super.onResume();
        loadContacts(true);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        contactViewModel.contactListUpdatedLiveData().observeForever(contactListUpdateLiveDataObserver);
        contactViewModel.friendRequestUpdatedLiveData().observeForever(friendRequestUpdateLiveDataObserver);

        userViewModel = WfcUIKit.getAppScopeViewModel(UserViewModel.class);
        userViewModel.userInfoLiveData().observeForever(userInfoLiveDataObserver);
        UserInfo userInfo = userViewModel.getUserInfo(userViewModel.getUserId(), true);
        if (userInfo != null) {
            this.userInfo = userInfo;
        }

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        contactViewModel.contactListUpdatedLiveData().removeObserver(contactListUpdateLiveDataObserver);
        contactViewModel.friendRequestUpdatedLiveData().removeObserver(friendRequestUpdateLiveDataObserver);
        userViewModel.userInfoLiveData().removeObserver(userInfoLiveDataObserver);
    }

    @Override
    public void initHeaderViewHolders() {
        addHeaderViewHolder(AddFriendViewHolder.class, new HeaderValue());
        addHeaderViewHolder(FriendRequestViewHolder.class, new FriendRequestValue(contactViewModel.getUnreadFriendRequestCount()));
    }

    @Override
    public void initFooterViewHolders() {
        addFooterViewHolder(ContactCountViewHolder.class, new ContactCountFooterValue());
    }

    @Override
    public void onUserClick(UIUserInfo userInfo) {
        Intent intent = new Intent(getActivity(), UserInfoActivity.class);
        intent.putExtra("userInfo", userInfo.getUserInfo());
        if (this.userInfo != null) {
            intent.putExtra("MyUID", this.userInfo.uid);
        }
        startActivity(intent);
    }

    @Override
    public void onHeaderClick(int index) {
        switch (index) {
            case 0:
                // 添加朋友
                searchUser();
                break;
            case 1:
                // 新的朋友
                contactViewModel.clearUnreadFriendRequestStatus();
                ((MainActivity) getActivity()).hideUnreadFriendRequestBadgeView();
                showFriendRequest();
                break;
            default:
                break;
        }
    }

    private void searchUser() {
        Intent intent = new Intent(getContext(), SearchUserActivity.class);
        intent.putExtra("search_type", SearchActivity.TYPE_USER_SEARCH);
        intent.putExtra("style", "add_friend");
        startActivity(intent);
    }

    /**
     * modify by HEKE , 2019/8/28 10:33 TODO 在用户关闭应用消息通知时，开启允许手动刷新显示好友请求
     */
    public void refreshFriendRequestSignWithAppNoNotufyPermission() {
        if (contactViewModel == null) {
            return;
        }
        contactViewModel.getUnreadFriendRequestCount();
        contactViewModel.contactListUpdatedLiveData().observeForever(contactListUpdateLiveDataObserver);
        contactViewModel.friendRequestUpdatedLiveData().observeForever(friendRequestUpdateLiveDataObserver);
        userViewModel.userInfoLiveData().observeForever(userInfoLiveDataObserver);
    }

    private void showFriendRequest() {
        ((MainActivity) getActivity()).hideUnreadFriendRequestBadgeView();
        FriendRequestValue value = new FriendRequestValue(0);
        /**
         * modify by HEKE , 2019/9/10 18:20 TODO HEKE，标注需要刷新的数据位置，新的朋友数值标记问题
         */
        userListAdapter.updateHeader(1, value);
        contactViewModel.clearUnreadFriendRequestStatus();
        Intent intent = new Intent(getActivity(), FriendRequestListActivity.class);
        startActivity(intent);
    }

}
